
    /**  
    * @Title: AbstractStatefulJobBean.java
    * @Package com.efast.cafe.commponent.job.base
    * @Description: TODO(用一句话描述该文件做什么)
    * @author Administrator
    * @date 2018年9月13日
    * @version V1.0  
    */
    
package com.efast.cafe.commponent.job.base;

import org.quartz.DisallowConcurrentExecution;
import org.quartz.Job;
import org.quartz.JobDataMap;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.quartz.SchedulerException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanWrapper;
import org.springframework.beans.BeanWrapperImpl;
import org.springframework.beans.MutablePropertyValues;

import com.efast.cafe.commponent.job.bean.ScheduleExecuteLog;

/**
    * @ClassName: AbstractStatefulJobBean
    * @Description: 此标记用在实现Job的类上面,意思是不允许并发执行.
    * org.quartz.threadPool.threadCount线程池中线程的数量至少要多个,否则@DisallowConcurrentExecution不生效
    * @author Administrator
    * @date 2018年9月13日
    *
    */
@DisallowConcurrentExecution
public abstract class AbstractStatefulJobBean implements Job{

	public Logger logger = LoggerFactory.getLogger(getClass());

	
	    /* (非 Javadoc)
	    * 
	    * 
	    * @param context
	    * @throws JobExecutionException
	    * @see org.quartz.Job#execute(org.quartz.JobExecutionContext)
	    */
	    
	@Override
	public void execute(JobExecutionContext context) throws JobExecutionException {
		try {
			// set properties from job data map to job instance.
			JobDataMap jobDataMap = context.getMergedJobDataMap();
			BeanWrapper bw = new BeanWrapperImpl(this);
			MutablePropertyValues pvs = new MutablePropertyValues();
			pvs.addPropertyValues(context.getScheduler().getContext());
			pvs.addPropertyValues(jobDataMap);
			bw.setPropertyValues(pvs, true);
			// get job name from context, job name for logging.
			String jobName = context.getJobDetail().getKey().getName();
			long startTime = System.currentTimeMillis();
			
			ScheduleExecuteLog log = ScheduleExecuteLog.getInstance(jobName); 
			log.clearLogs();
			log.putLog("Start： [" + jobName + "] execution.");
			logger.info("Start： [" + jobName + "] execution.");
			executeInternal(context,log);// execute internal job.
			logger.info("End：  [" + jobName + "] execution.");
			long endTime = System.currentTimeMillis();
			log.putLog("Running Job has been completed , cost time :  " + (endTime - startTime)+" ms.");
			
			//context.getTrigger().getJobDataMap().put(JOB_LAST_TIME_ELLAPSE,ellapse);
		}catch (SchedulerException ex) {
			logger.error("Failed： [" + context.getJobDetail().getKey().getName() + "] execution.",ex);
			throw new JobExecutionException(ex);
		}
	}
	
	
	/**
	 * Execute true job.
	 * 
	 * @param context
	 * @throws JobExecutionException
	 */
	protected abstract void executeInternal(JobExecutionContext context,ScheduleExecuteLog log)
			throws JobExecutionException;
}
